﻿using MediatR;
using W.Product.API.Appliaction.CommandHandler.ReportlossesCommandHandler;
using W.Warehouse.Api.Application.Command.ReportlossesCommand;
using W.Warehouse.Repository.Interface;

namespace W.Warehouse.Api.Application.CommandHandlder.ReportlossesCommandHandler
{
    public class ReportlossesRangeDelCommandHandler : IRequestHandler<ReportlossesRangeDelCommand, ApiResult<int>>
    {
        private readonly ILogger<ReportlossesRangeDelCommandHandler> _logger;
        private readonly IReportlossesRepository reportlossesRepository;
        private readonly IReportProductRepository productRepository;
        public ReportlossesRangeDelCommandHandler(IReportlossesRepository reportlossesRepository, IReportProductRepository productRepository,
            ILogger<ReportlossesRangeDelCommandHandler> logger)
        {
            this.reportlossesRepository = reportlossesRepository;
            this.productRepository = productRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(ReportlossesRangeDelCommand request, CancellationToken cancellationToken)
        {
           ApiResult<int> result=new ApiResult<int>();
            try
            {
                var list = await reportlossesRepository.GetAllAsync();
                var lists = list.Where(x=>request.ReportlossesId.Contains(x.ReportlossesId)).ToList();
                lists.ForEach(x =>
                {
                    x.IsDelete = true;
                    x.DeleteTime = DateTime.Now;
                });
                var res=await productRepository.GetAllAsync();
                var ress=res.Where(x=>request.ReportlossesId.Contains(x.ReportProductId)).ToList();
                ress.ForEach(x =>
                {
                    x.IsDelete= true;
                    x.DeleteTime = DateTime.Now;
                });

                 await reportlossesRepository.UpdateRangeAsync(lists);
                await productRepository.UpdateRangeAsync(ress);
                result.Code = 1;
                _logger.LogInformation("批量删除报损管理成功");
                return result;

            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                _logger.LogError(ex, ex.Message);
                throw;
            }
        }
    }
}
